package utils;

import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.ListView;

/**
 * Created by Administrator on 2017/3/16.
 * 计算工具
 */

public class CalculateUtils {
    //计算listview高度
    public static void calculateListViewHeight(ListView pull, Adapter adapter){
        int totalHeight = 0;
        for (int i = 0, len = adapter.getCount(); i < len; i++) { //listAdapter.getCount()返回数据项的数目
            View listItem = adapter.getView(i, null, pull);
            listItem.measure(0, 0); //计算子项View 的宽高
            totalHeight += (listItem.getMeasuredHeight()); //统计所有子项的总高度
        }
        ViewGroup.LayoutParams params = pull.getLayoutParams();
        params.height = totalHeight + (pull.getDividerHeight() * (pull.getCount() - 1));
        pull.setLayoutParams(params);
    }
    //计算gridView工具
    public static void setListViewHeightBasedOnChildren(GridView listView) {
        // 获取listview的adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        // 固定列宽，有多少列
        int col = listView.getNumColumns();
        int totalHeight = 0;
        // i每次加4，相当于listAdapter.getCount()小于等于4时 循环一次，计算一次item的高度，
        // listAdapter.getCount()小于等于8时计算两次高度相加
        View listItem = null;
        if(listAdapter.getCount()>0){
            // 获取listview的每一个item
            listItem = listAdapter.getView(0, null, listView);
            listItem.measure(0, 0);
        }
        if(listItem!=null) {
            for (int i = 0; i < listAdapter.getCount(); i += col) {
                // 获取item的高度和
                totalHeight += listItem.getMeasuredHeight();
            }
        }
        // 获取listview的布局参数
        ViewGroup.LayoutParams params =  listView.getLayoutParams();
        // 设置高度
        params.height = totalHeight;
        // 设置参数
        listView.setLayoutParams(params);
    }


}
